package com.xinggq.pay.service.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring上下文持有者工具类
 * @Description 用于在非Spring管理的类中获取Spring Bean
 * @Author xinggq
 * @Date 2025/9/9
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
  
  private static ApplicationContext applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextHolder.applicationContext = applicationContext;
  }

  /**
   * 获取Spring应用上下文
   */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  /**
   * 根据Class获取Bean实例
   */
  public static <T> T getBean(Class<T> clazz) {
    if (applicationContext == null) {
      throw new IllegalStateException("Spring应用上下文未初始化");
    }
    return applicationContext.getBean(clazz);
  }

  /**
   * 根据Bean名称获取Bean实例
   */
  public static Object getBean(String beanName) {
    if (applicationContext == null) {
      throw new IllegalStateException("Spring应用上下文未初始化");
    }
    return applicationContext.getBean(beanName);
  }

  /**
   * 根据Bean名称和Class获取Bean实例
   */
  public static <T> T getBean(String beanName, Class<T> clazz) {
    if (applicationContext == null) {
      throw new IllegalStateException("Spring应用上下文未初始化");
    }
    return applicationContext.getBean(beanName, clazz);
  }

  /**
   * 检查Spring上下文是否已初始化
   */
  public static boolean isInitialized() {
    return applicationContext != null;
  }
}